//
//  ContentView.swift
//  woodenfishwatch Watch App
//
//  Created by 李志祥 on 2025/3/12.
//

import SwiftUI
import AVFoundation

struct ContentView: View {
    @State private var meritCount: Int = 0
    @State private var isAnimating: Bool = false
    @State private var audioPlayer: AVAudioPlayer?
    
    init() {
        // 直接使用Bundle.main.url来加载音频文件
        print("开始初始化音频播放器")
        if let soundURL = Bundle.main.url(forResource: "WoodenFishSound", withExtension: "mp3") {
            print("找到音频文件: \(soundURL.path)")
            do {
                audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
                audioPlayer?.prepareToPlay()
                print("音频播放器初始化成功")
            } catch {
                print("无法加载木鱼音效: \(error.localizedDescription)")
            }
        } else {
            print("未找到音频文件WoodenFishSound.mp3")
        }
    }
    
    var body: some View {
        ZStack {
            Color.black
                .edgesIgnoringSafeArea(.all)
            
            VStack {
                Text("功德：\(meritCount)")
                    .font(.system(size: 24, weight: .light, design: .default))
                    .foregroundColor(.white)
                    .padding()

                // 修改这里的图片引用，使用实际的图片名称而不是"Image"
                Image("WoodenFish")
                    .resizable()
                    .frame(width: 100, height: 100)
                    .scaleEffect(isAnimating ? 0.9 : 1.0)
                    .animation(.spring(response: 0.3, dampingFraction: 0.6), value: isAnimating)
                    .onTapGesture {
                        tapWoodenFish()
                    }
                    .padding()
                
                Text("点击木鱼积累功德")
                    .font(.system(size: 16, weight: .light, design: .default))
                    .foregroundColor(.white)
                    .padding()
            }
            .padding()
        }
    }
    
    private func tapWoodenFish() {
        // 播放音效
        print("尝试播放音效")
        if let player = audioPlayer {
            player.volume = 1.0
            let playResult = player.play()
            
            print("播放结果: \(playResult)")
        } else {
            print("音频播放器未初始化")
        }
        
        // 增加功德计数
        meritCount += 1
        
        // 触发动画
        isAnimating = true
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            isAnimating = false
        }
    }
}

#Preview {
    ContentView()
}
